#include "client.h"
#include "ui_client.h"

client::client(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::client)
{
    ui->setupUi(this);
    setWindowTitle("客户端");
    ksocket = new QTcpSocket(this);
    QString ip="127.0.0.1";
    unsigned short port=9999;
    ksocket->connectToHost(QHostAddress(ip),port);
    ui->lineEdit_ip->setText("127.0.0.1");
    ui->lineEdit_port->setText("9999");
    connect(ui->btn_connect,&QPushButton::clicked,ksocket,[=](){
        tryConnect(ksocket);
    });
    connect(ksocket, &QTcpSocket::connected, this, &client::connectToServer);
    connect(ksocket,&QTcpSocket::readyRead,this,&client::readmessage);
    connect(ksocket,&QTcpSocket::disconnected,this,[=]()
    {
        ksocket->close();
        ui->message_textBrowser->append("断开连接");
    });
}

client::~client()
{
    delete ui;
}

void client::connectToServer()
{
    ui->message_textBrowser->append("成功和服务器进行连接");
}

void client::tryConnect(QTcpSocket* ksocket){
    QString ip=ui->lineEdit_ip->text();
    unsigned short port=ui->lineEdit_port->text().toInt();
    //unsigned short port=9999;
    ksocket->connectToHost(QHostAddress(ip),port);
}

void client::send_foodmsg(QString food)
{
    QString msg=food;
    if(msg=="")
    {
        return;
    }
    ksocket->write(msg.toUtf8());
    ui->message_textBrowser->append("客户端："+msg);
    ui->send_textBrowser->clear();
}

void client::on_send_pushButton_clicked()
{
    QString msg=ui->send_textBrowser->toPlainText();
    if(msg=="")
    {
        return;
    }
    ksocket->write(msg.toUtf8());
    ui->message_textBrowser->append("客户端："+msg);
    ui->send_textBrowser->clear();
}
void client::readmessage()
{
    QByteArray data=ksocket->readAll();
    ui->message_textBrowser->append("服务端："+data);
}
